// $Id: ArrayEnumerable.java 10 2012-11-25 04:28:25Z marcel.kloubert $

/*****************************************************************************
 *                                                                           *
 *   Licensed to the Apache Software Foundation (ASF) under one              *
 *   or more contributor license agreements.  See the NOTICE file            *
 *   distributed with this work for additional information                   *
 *   regarding copyright ownership.  The ASF licenses this file              *
 *   to you under the Apache License, Version 2.0 (the                       *
 *   "License"); you may not use this file except in compliance              *
 *   with the License.  You may obtain a copy of the License at              *
 *                                                                           *
 *       http://www.apache.org/licenses/LICENSE-2.0                          *
 *                                                                           *
 *   Unless required by applicable law or agreed to in writing,              *
 *   software distributed under the License is distributed on an             *
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY                  *
 *   KIND, either express or implied.  See the License for the               *
 *   specific language governing permissions and limitations                 *
 *   under the License.                                                      *
 *                                                                           *
 *****************************************************************************/


package net.metalvz.linq;

import java.util.Arrays;
import java.util.Iterator;

/**
 * A sequence that uses an array.
 * 
 * @author Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
 *
 * @param <T> Type of the items of the array.
 */
public final class ArrayEnumerable<T> extends EnumerableBase<T> {
	private final T[] _ARRAY;
	
	/**
	 * Initializes a new instance of that class.
	 * 
	 * @param seq The inner sequence.
	 */
	public ArrayEnumerable(T[] array) {
		this._ARRAY = array;
	}

	@Override
	public int count() {
		return this._ARRAY.length;
	}
	
	@Override
	public int indexOf(T itemToSearch) {
		int result = -1;
		
		int currentIndex = 0;
		for (T item: this._ARRAY) {
			boolean found = false;
			if (item == null) {
				found = itemToSearch == null;
			}
			else {
				found = item.equals(itemToSearch);
			}
			
			if (found) {
				result = currentIndex;
				break;
			}
			
			++currentIndex;
		}
		
		return result;
	}
	
	@Override
	public Iterator<T> iterator() {
		return Arrays.asList(this._ARRAY).iterator();
	}
}
